package cn.swenty.backstage.framework.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import cn.swenty.backstage.framework.database.mapper.BasicMapper;


/**
 * 通过初始化一个bean，获取spring bean的一些基本信息，并对外提供一些方法
 * 
 * @author sunyang
 *
 */
public class ServiceFactory implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
	
	/* 
	 * 通过配置文件注入
	 * (non-Javadoc)
	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
	 */
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		ServiceFactory.applicationContext = arg0;
	}

	/**
	 * @param name 通过名字获取
	 * @return
	 */
	public static Object getBean(String name) {
		if(applicationContext == null) return null;
		return applicationContext.getBean(name);
	}
	
	
	/**
	 * 
	 * 通过类的类型获取bean
	 * @param className
	 * @return
	 */
	public static <T extends BaseService> T getService(Class<T> className) {
		if(applicationContext == null) return null;
		return applicationContext.getBean(className);
	}
	
	/**
	 * 
	 * 通过类的类型获取bean
	 * @param className
	 * @return
	 */
	public static <T> T getBean(Class<T> className) {
		if(applicationContext == null) return null;
		return applicationContext.getBean(className);
	}
	
	/**
	 * 通过mapper类型获取mapper
	 * @param mapper 
	 * @return
	 */
	public  static <T extends BasicMapper> T getMapper(Class<T> mapper){
		if(applicationContext == null) return null;
		return getSqlSession().getMapper(mapper);
	}
	
	/**
	 * 
	 * 获取系统的sqlSessionFactory，一定和配置文件中保持一致
	 * @return
	 */
	public static SqlSession getSqlSession(){
		if(applicationContext == null) return null;
		try {
			return ((SqlSessionFactory)applicationContext.getBean("sqlSessionFactory")).openSession();
		} catch (BeansException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static SqlSession getCurrentSqlSession(){
		if(applicationContext == null) return null;
		return SqlSessionUtils.getSqlSession((SqlSessionFactory)applicationContext.getBean("sqlSessionFactory"));
	}
	
	
}
